package com.lnu_devteam.zongce.interceptor;

import com.lnu_devteam.zongce.common.ErrorCode;
import com.lnu_devteam.zongce.exception.BusinessException;
import com.lnu_devteam.zongce.model.entity.User;
import com.lnu_devteam.zongce.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author xbaozi
 * @version 1.0
 * @classname LoginInterceptor
 * @date 2023-04-06  16:32
 * @description 登录拦截器
 */
@Aspect
@Component
@Slf4j
public class LoginInterceptor {

    @Resource
    private UserService userService;

    @Before("execution(* com.lnu_devteam.zongce.controller.*.*(..)) && !execution(* com.lnu_devteam.zongce.controller.*.login(..))")
    public void doInterceptor() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        User user = userService.getLoginUser(httpServletRequest);
        if (user == null) {
            log.error("try to access {} but not login...", httpServletRequest.getRequestURI());
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        userService.refreshAuth();    }
}
